package cn.isekai.keycloak.avatar.storage;

import cn.isekai.keycloak.avatar.utils.ImageUtils;
import org.jboss.logging.Logger;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public abstract class AvatarStorageProviderAbstract implements AvatarStorageProvider {
    private static final Logger logger = Logger.getLogger(AvatarStorageProviderAbstract.class);

    @Override
    public boolean saveOriginalAvatarImage(String realmName, String userId, String avatarId, InputStream input,
                                           AvatarCropParams cropParams, Map<String, Integer> sizeList) {
        try {
            boolean succeed = true;

            // 首先读取原始图片到 BufferedImage
            BufferedImage originalImage = ImageUtils.inputStreamToBufferedImage(input);
            if (originalImage == null) {
                logger.error("Failed to read image from input stream");
                return false;
            }

            // 如果需要裁剪，先进行裁剪
            BufferedImage processedImage = originalImage;
            if (cropParams != null) {
                processedImage = ImageUtils.cropImage(originalImage, cropParams.x, cropParams.y, cropParams.size);
            }

            // 处理每个尺寸
            for (Map.Entry<String, Integer> entries : sizeList.entrySet()) {
                // 调整到目标尺寸
                BufferedImage resizedImage = ImageUtils.resizeImage(processedImage, entries.getValue(), entries.getValue());

                // 转换为 InputStream
                InputStream resizedImageStream = ImageUtils.bufferedImageToInputStream(resizedImage, "PNG");

                // 保存对应尺寸的文件
                succeed = succeed && this.saveAvatarImage(realmName, userId, avatarId, resizedImageStream, entries.getKey());
                resizedImageStream.close();
            }
            return succeed;
        } catch (IOException ex) {
            logger.error("Failed to process avatar image", ex);
            return false;
        }
    }
}
